/****************
 *@description: 新增/修改 搜索热词
 *@author: Xhd
 *@date: 2023-04-07 15:30:44
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { Form, Input, InputNumber, Select, Space, Button, Modal } from "antd";
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import List from '@/views/settings/shuffling/component/carousellist'
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack';
import { apiActivityLinkList } from "@/request/h5";
import { apiShopKeywordDetail, apiSaveOrUpdateShopKeyword } from "@/request/app/hotsearch.js";
 
const { Option } = Select
const formItemLayout = {
  labelCol: {
      xs: { span: 24 },
      sm: { span: 3 },
  },
  wrapperCol: {
      xs: { span: 24 },
      sm: { span: 8 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 20, offset: 4 },
  },
};
class Hotsearch extends Component {
  constructor(props){
    super(props)
    this.state = {
      title:'新增',
      keywordList:[
        { key: '商品搜索', value: '19'},
        { key: '地址链接', value: '1'},
        { key: '商城商品', value: '3'},
        { key: '线下门店', value: '4'},
        { key: '线下商品', value: '5'},
        { key: '邀请有礼', value: '7'},
        { key: '砍一刀', value: '8'},
        { key: '我的卡包', value: '10'},
        { key: '宠物出行', value: '11'},
        { key: '正品保障', value: '12'},
        { key: '领券中心', value: '20'},
        // { key: '宠物打车', value: '13'},
        // { key: '宠物酒店', value: '14'},
        // { key: '宠物医院', value: '15'},
        // { key: '洗护美容', value: '16'},
        // { key: '商品分类', value: '17'},
      ],
      initialValues: {
        keywordType: '19',
        keyword:'',
        sort:'',
      },
      radioValue:'19',
      activeList:[],
      configCarouselUri:'',
      arr:[],
      visible:false,
      keywordId:''
    }
  }

  componentDidMount() {
    this.getActiveList()
    if(this.props.match.params.type === 'edit'){
      this.setState({
        title:'修改',
        keywordId:this.props.match.params.id
      }, async ()=>{
        let res = await apiShopKeywordDetail({keywordId:this.state.keywordId})
        if(res.code === 0){
          let data = res.data
          if (data.keywordType !== '1') {
            if (data.linkUrl !== '') {
              this.setState({
                configCarouselUri: data.linkUrl
              })
            }
          }else {
            let users = []
            let url = []
            if (data.linkUrl.indexOf('?') != '-1') {
              url = data.linkUrl.split('?')
              console.log(url);
              data.linkUrl = url[0]
              users = url[1].split('&')
              let str = ''
              users.map((item) => {
                str = item.split('=')
                let arr = []
                arr.push({
                  key: str[0],
                  value: str[1]
                })
                this.setState({ arr })
              })
            } else {
              data.linkUrl = data.linkUrl.trim()
            }
          }
          this.setState({
            initialValues:{
              keyword:data.keyword,
              sort:data.sort,
              keywordType:data.keywordType,
              configCarouselUri:data.linkUrl,
            },
            radioValue:data.keywordType,
            configCarouselUri:data.linkUrl,
          },()=>{
            this.formRef.setFieldsValue({ ...this.state.initialValues })
          })
        }
      })
    }
  }

  getData = () => {

  }
  // 外链地址下拉内容
  async getActiveList() {
    await apiActivityLinkList().then(res => {
      if (res.code === 0) {
        this.setState({
          activeList: res.data
        })
      }
    })
  } 

  keyWordTypeChange = (e) =>{
    this.setState({
      configCarouselUri: ''
    }, () => {
      this.formRef.setFieldsValue({ configCarouselUri: '', users: '' })
      const CarouselType = e
      if (CarouselType !== '1') {
        this.openMadol(CarouselType)
      } else {
        this.setState({
          configCarouselUri: '',
          users: ''
        })
      }
      this.setState({
        radioValue: e,
      })
    })
  }

  configCarouselUriChange = (e) => {
    this.formRef.setFieldsValue({ users: '' })
    this.setState({ configCarouselUri: e })
  }

  openMadol = (CarouselType) => {
    switch (CarouselType) {
      case '2':
        this.setState({
          visible: true,
          typetitle: '商城门店'
        })
        break;
      case '3':
        this.setState({
          visible: true,
          typetitle: '商城商品'
        })
        break;
      case '4':
        this.setState({
          visible: true,
          typetitle: '线下门店'
        })
        break;
      case '5':
        this.setState({
          visible: true,
          typetitle: '线下商品'
        })
        break;
      case '6':
        this.setState({
          visible: true,
          typetitle: '服务'
        })
        break;
      case '9':
        this.setState({
          visible: true,
          typetitle: '服务类目'
        })
        break;
      case '14':
        this.setState({
          visible: true,
          typetitle: '宠物酒店'
        })
        break;
      case '15':
        this.setState({
          visible: true,
          typetitle: '宠物医院'
        })
        break;
      case '16':
        this.setState({
          visible: true,
          typetitle: '洗护美容'
        })
        break;
      default:
        break;
    }
  }
  onCancel = () => {
    this.setState({
      visible: false
    })
  }

  goDetail(param) {
    let { type, typeId, typeName, storeId, storeName } = param;
    switch (type) {
      case '2':
      const mallobj = { storeId: typeId, storeName: typeName }
      const mallCarouselUri = JSON.stringify(mallobj);
      // console.log(mallobj, mallCarouselUri)
      this.setState({
          visible: false,
          configCarouselUri: mallCarouselUri
      }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
      })

      break;
      case '3':
        const goodsobj = { goodsId: typeId, goodsName: typeName, storeId: storeId, storeName: storeName }
        const goodsCarouselUri = JSON.stringify(goodsobj);
        this.setState({
            visible: false,
            configCarouselUri: goodsCarouselUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '4':
        const storeobj = { storeId: typeId, storeName: typeName }
        const storeCarouselUri = JSON.stringify(storeobj);
        this.setState({
            visible: false,
            configCarouselUri: storeCarouselUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '14':
        const hotelobj = { storeId: typeId, storeName: typeName, type: 'HOTEL' }
        const hotelUri = JSON.stringify(hotelobj);
        this.setState({
            visible: false,
            configCarouselUri: hotelUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '15':
        const hospitalobj = { storeId: typeId, storeName: typeName, type: 'HOSPITAL' }
        const hospitalUri = JSON.stringify(hospitalobj);
        this.setState({
            visible: false,
            configCarouselUri: hospitalUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '16':
        const hairdressobj = { storeId: typeId, storeName: typeName, type: "HAIRDRESSING" }
        const hairdressUri = JSON.stringify(hairdressobj);
        this.setState({
            visible: false,
            configCarouselUri: hairdressUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '5':
        const productobj = { productId: typeId, productName: typeName, storeId: storeId, storeName: storeName }
        const productCarouselUri = JSON.stringify(productobj);
        this.setState({
            visible: false,
            configCarouselUri: productCarouselUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '6':
        const serviceobj = { serviceId: typeId, serviceName: typeName, storeId: storeId, storeName: storeName }
        const serviceCarouselUri = JSON.stringify(serviceobj);
        this.setState({
            visible: false,
            configCarouselUri: serviceCarouselUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '9':
        const categoryobj = { serviceClassifyId: typeId, serviceClassifyName: typeName, }
        const serviceCategorylUri = JSON.stringify(categoryobj);
        this.setState({
            visible: false,
            configCarouselUri: serviceCategorylUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: `${typeName}` })
        })
        break;
      default:
        break;
    }
}
  getStringName(carouselUri, type) {
    let str = ''
    if (type !== '1') {
      if (carouselUri !== '') {
        carouselUri = JSON.parse(carouselUri)
        switch (type) {
          case '2':
            str = carouselUri.storeName
            break;
          case '3':
            str = carouselUri.goodsName + carouselUri.storeName
            break;
          case '4': case '14': case '15': case '16':
            str = carouselUri.storeName
            break;
          case '5':
            str = carouselUri.productName + carouselUri.storeName
            break;
          case '6':
            str = carouselUri.serviceName + carouselUri.storeName
            break;
          case '7':
            str = ''
            break;
          case '8':
            str = ''
            break;
          case '9':
            str = carouselUri.serviceClassifyName
            break;
          case '10':
            str = ''
            break;
          case '11':
            str = ''
            break;
          case "12":
            str = ""
            break;
          case "13":
            str = ""
            break;
          default:
            str = ""
            break;
        }
      }
    }
    return str
  }

  onFinish = async (value) => {
    if (this.state.radioValue !== '1') {
      value.configCarouselUri = this.state.configCarouselUri
    } else {
      value.configCarouselUri = value.configCarouselUri.trim()
    }
    let str = ''
    if (value.users && value.users.length !== 0) {
      value.users.map((item, index) => {
        str += item.key + '=' + item.value
        if (index + 1 !== value.users.length) {
          str += '&'
        }
        return str
      })
      value.configCarouselUri = value.configCarouselUri.trim() + '?' + str
      delete value.users
    }
    value.linkUrl = value.configCarouselUri
    if(this.state.keywordId){
      value.keywordId = this.state.keywordId
      let res = await apiSaveOrUpdateShopKeyword(value)
      if(res.code === 0){
        React.$message({
          type:'success',
          content:'修改成功'
        })
        this.props.history.go(-1)
      }
    }else{
      let res = await apiSaveOrUpdateShopKeyword(value)
      if(res.code === 0){
        React.$message({
          type:'success',
          content:'新增成功'
        })
        this.props.history.go(-1)
      }
    }
  }

  render(){
    const { title, keywordList, radioValue, initialValues, activeList, configCarouselUri, arr, visible, typetitle } = this.state
    return <div className="p-layout-box">
        <GoBack history={this.props.history} title={title} />
        <br />
        <Form 
          ref={(ref) => {
            this.formRef = ref;
          }}
          {...formItemLayout}
          labelAlign='right'
          initialValues={initialValues}
          onFinish={this.onFinish}
        >
          <Form.Item rules={[{ required: true, message: '请输入' },{max: 20, message: '最大输入20个字符' }]} name={'keyword'} label='关键词' >
            <Input maxLength={20} showCount/>
          </Form.Item>
          <Form.Item rules={[{ required: true, message: '请输入' },{pattern: /^(0|\+?[1-9][0-9]{0,4})$/ ,message:'可填写范围为0~99999',},]} name={'sort'} label='序号' >
            <InputNumber />
          </Form.Item>
          <Form.Item rules={[{ required: true, message: '请选择' }]} name={'keywordType'} label={'跳转链接'}>
            <Select onChange={this.keyWordTypeChange} initialValues={radioValue} >
              {keywordList.map(item => <Option value={item.value}>{item.key}</Option>)}
            </Select>
          </Form.Item>
          {radioValue === '' ? <Form.Item
              name={'configCarouselUri'}
              label={'地址链接'}>
              <Input />
            </Form.Item> :
            (radioValue === '7' || radioValue === '8' || radioValue === '10' || radioValue === '11' || radioValue === '12' || radioValue === '13' || radioValue === '19' || radioValue === '20') ?
              <Form.Item name={'configCarouselUri'}
                  label={'选择链接'}>
                  <Input readOnly placeholder="无需填写" />
              </Form.Item> :
              <Form.Item name={'configCarouselUri'}
                label={'选择链接'}
                rules={[{ required: radioValue !== 1 ? true : false, message: '请选择链接' }]}
              >
                {radioValue === '1' ? <Select onChange={this.configCarouselUriChange}>
                    {
                      activeList.map(item => <Option value={item.activityLink} key={item.id}>{item.activityName}</Option>)
                    }

                </Select> : <div style={{ border: '1px solid #ccc', lineHeight: '28px', paddingLeft: '10px', minHeight: '30px' }}>
                    {
                      this.getStringName(configCarouselUri, radioValue)
                    }

                </div>}
              </Form.Item>
          }
          {
            radioValue === '1' && configCarouselUri !== '' ? <Form.List name="users" initialValue={arr}>
                {(fields, { add, remove }) => (
                    <>
                        <Form.Item label="参数">
                            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                添加参数
                            </Button>
                        </Form.Item>
                        {fields.map(({ key, name, ...restField }) => (
                            <Form.Item
                                {...formItemLayoutWithOutLabel}
                                required={false}
                                key={key}
                                style={{
                                    margin: 0
                                }}
                            >
                                <Space
                                    style={{
                                        display: 'flex',
                                        marginBottom: 0,
                                    }}
                                    align="baseline"
                                >
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'key']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入参数名',
                                            },
                                        ]}

                                    >
                                        <Input placeholder="参数名" />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'value']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入参数值',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="参数值" />
                                    </Form.Item>
                                    <CloseCircleOutlined onClick={() => remove(name)} />
                                </Space>
                            </Form.Item>
                        ))}

                    </>
                )}
            </Form.List> : ''
          }
          <Form.Item label=' ' colon={false} labelCol={{ xs: { span: 12 }, sm: { span: 5 },}}>
            <div>
              <Space>
                <TheButton type="primary" size="middle" htmlType="primary" >保存</TheButton>
                <TheButton type="default" size="middle" onClick={()=>this.props.history.go(-1)} >取消</TheButton>
              </Space>
            </div>
          </Form.Item>
        </Form>
        <Modal
          visible={visible}
          onCancel={this.onCancel}

          title={typetitle}
          width='1000px'
          destroyOnClose={true}
          footer={null}
        >
          <List radiotype={radioValue} getList={(e) => this.goDetail(e)} />
        </Modal>
    </div>
  }
}

export default Hotsearch
